//
// Created by ubuntu20-04 on 10/27/22.
//
#pragma once

#include <stdint.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include "rc.h"
#include "sql/parser.parse_defs.h"

inline bool is_leap_year (int year) {
  return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

inline RC string_to_date(const char *str, int32_t &date) {
  int year = 0;
  int month = 0;
  int day = 0;
  int ret = sscanf(str, "%d-%d-%d", &year, &month, &day);
  if(ret != 3) {
    return RC::INVALID_ARGUMENT;
  }
  //invalid date
  int max_day_in_month[] = {31, 29, 31, 30,31,30,31,31,30,31,30,31};
  const int max_day = max_day_in_month[month -1];
  if(year <1970 || (year >=2038 && month > 2) ||
      (month <=0 || month >= 12) ||
      (day <=1 || day >= 31)) {
    return RC::INVALID_ARGUMENT;
  }
  if(day > max_day){
    return RC::INVALID_ARGUMENT;
  }
  if(month == 2 && !is_leap_year(year) && day>28) {
    return RC::INVALID_ARGUMENT;
  }
  return RC::SUCCESS;
}
class Date {
public:
  Date(char *str) {
    int y, m, d;
    sscanf(str, "%d-%d-%d",&y, &m, &d);
    date_ = y * 10000 + m * 100 + d;
    valid_ = isValidDate();
    std::stringstream ss;
  }

  bool isvalid(){
    return valid_;
  }

  std::string toString() {
    std::stringstream ss;
    ss << date_/10000 << "-" << date_ % 10000 / 100 << "-" << date_ % 100;
    return ss.str();
  }

  bool operator < (const Date& that) const{
    return this->date_ < that.date_;
  }

  bool operator == (const Date& that) const {
    return this->date_ == that.date_;
  }

private:
  bool isValidDate() const
  {
    static int max_day_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int y = date_ / 10000, m = date_ % 10000 / 100, d = date_ % 100;
    bool is_leap = (y % 400 == 0 || (y % 100 && y % 4 == 0));
    return y >= 1970 && y <= 2038 && (m > 0) && (m <= 12) && (d > 0) &&
           (d <= ((m == 2 && is_leap) ? 1 : 0) + max_day_in_month[m]);
  }

private:
  //将data字段转换为一个int32_t类型进行存储
  bool valid_;
  int32_t date_;
};



